import { createStore } from 'vuex'
import { login,getinfo,getinfos } from '~/api/manager'
import { toast } from '~/composables/util'

import {
    setToken,
    removeToken
} from '~/composables/auth'
const store = createStore({
    state() {
        return {
            // 用户信息
            user: {},
            // 侧边宽度
            asideWidth:"250px",
            //菜单
            menus:[],
            //权限菜单
            ruleNames:[],
            //面包屑
            breadCrumb:[]
        }
    },
    mutations: {
        // 记录用户信息
        SET_USERINFO(state,user){
            state.user = user.user_info ? user.user_info : [] 
        },
        // 展开/缩起侧边
        handleAsideWidth(state){
            state.asideWidth = state.asideWidth == "250px" ? "64px" : "250px"
        },
        //菜单
        SET_MENUS(state,menus){
            state.menus = menus
        },
        //权限
        SET_RULE_NAMES(state,ruleNames){
            state.ruleNames = ruleNames
        },
    },
    actions:{
        // 登录
        login({ commit }, { username,password }){
            return new Promise((resolve,reject)=>{
                login(username,password).then(res=>{
                    if(res.code == 200){
                        setToken(res.data.token)
                        resolve(res)
                    }else{
                        toast(res.msg,'error')
                    }
                }).catch(err=>reject(err))
            })
        },
        // 获取当前登录用户信息
        getinfo({ commit }){
            return new Promise((resolve,reject)=>{
                getinfo().then(res=>{
                    if(res.code == 200){
                        commit("SET_USERINFO",res.data)
                        resolve(res)
                    }else{
                        toast(res.msg,'error')
                    }
                }).catch(err=>reject(err))
            })
        },
        //获取用户菜单信息
        getinfos({commit}){
            return new Promise((resolve,reject)=>{
                getinfos().then(res=>{
                    if(res.code == 200){
                        commit("SET_MENUS",res.data.user_menus)
                        resolve(res)
                    }else{
                        toast(res.msg,'error')
                    }
                }).catch(err=>reject(err))
            })
        },
        // 退出登录
        logout({ commit }){
            // 移除cookie里的token
            removeToken()
            // 清除当前用户状态 vuex
            commit("SET_USERINFO",{})
        }
    }
})

export default store